import requests
import pandas as pd
from bs4 import BeautifulSoup
import os

def scrape_weather():
    try:
        # 创建数据目录
        os.makedirs('data', exist_ok=True)

        # 获取网页（增加超时和重试机制）
        url = "http://www.weather.com.cn/weather/101010100.shtml"
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
            "Referer": "http://www.weather.com.cn/",
            "Accept-Language": "zh-CN,zh;q=0.9"
        }
        
        response = requests.get(url, headers=headers, timeout=15)
        response.encoding = 'utf-8' if 'utf-8' in response.headers.get('Content-Type', '').lower() else 'gbk'
        soup = BeautifulSoup(response.text, 'html.parser')

        # 精准解析实时温度（完全适配截图结构）
        today_temp = "N/A"
        
        # 关键修复：先定位父容器再找温度div
        sky_div = soup.find('div', class_='sk mySkyNull')
        if sky_div:
            tem_div = sky_div.find('div', class_='tem')
            if tem_div:
                span = tem_div.find('span')
                em = tem_div.find('em')
                if span and em:  # 确保两个标签都存在
                    today_temp = f"{span.text.strip()}{em.text.strip()}"  # 组合成"28.7℃"

        # 7天预报（保持原有成功逻辑）
        forecast_data = []
        for li in soup.select('.t.clearfix li'):
            date = li.find('h1').text if li.find('h1') else 'N/A'
            weather = li.find('p', class_='wea').text if li.find('p', class_='wea') else 'N/A'
            temp = li.find('p', class_='tem').text.strip() if li.find('p', class_='tem') else 'N/A'
            forecast_data.append([date, weather, temp])

        # 保存数据
        with pd.ExcelWriter('data/weather.xlsx', engine='openpyxl') as writer:
            pd.DataFrame({'城市': ['北京'], '温度': [today_temp]}).to_excel(writer, sheet_name='实时天气', index=False)
            pd.DataFrame(forecast_data, columns=['日期', '天气', '温度']).to_excel(writer, sheet_name='7天预报', index=False)

        print(f"实时温度: {today_temp}")
        print("数据已保存到 data/weather.xlsx")

    except Exception as e:
        print(f"错误: {str(e)}")

if __name__ == "__main__":
    scrape_weather()